package com.google.code.sfa.parse;

import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.lang.Iterable;

public class TraceIndex {

    private Map<Integer,List<Trace>> _index;
    private IntegerNMerParser _parser;

    public TraceIndex( int size) {
	_index = new HashMap<Integer,List<Trace>>();
	_parser = new IntegerNMerParser( size);
    }


    public void add( Trace trace) {
	_parser.reset( trace.getSequence() );
	List<Trace> list;
	while( _parser.advance() ) {
	    
	    if( _index.containsKey( _parser.current())) {
		list = _index.get( _parser.current());
		if( !list.contains( trace) ) {
		    list.add(trace);
		}
	    } else {
		list = new ArrayList<Trace>();
		_index.put( _parser.current(), list);
		list.add( trace);
	    }

	}

    }

    public Map<Trace,Integer> findMatches( Trace trace) {
	Map<Trace,Integer> matches = new HashMap<Trace,Integer>();
	List<Trace> list;
	_parser.reset( trace.getSequence() );
	while( _parser.advance() ) {
	    if( _index.containsKey( _parser.current() ) ) {
		list = _index.get( _parser.current());
		for( Trace match : list) {
		    if( matches.containsKey( match) ) {
			matches.put( match, matches.get(match) + 1);
		    } else {
			matches.put( match, 1);
		    }
		}
	    }
	}
	return matches;
    }
}